package com.softserveinc.moviedbapp.application;

import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.Menu;
import android.support.v4.view.MenuInflater;
import android.support.v4.view.MenuItem;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.softserveinc.moviedbapp.R;
import com.softserveinc.moviedbapp.fragment.MovieInfoFragment;
import com.softserveinc.moviedbapp.fragment.MovieItemsFragment;
import com.softserveinc.moviedbapp.fragment.MovieItemsFragment.OnMovieSelectedListener;
import com.softserveinc.moviedbapp.map.MapViewer;
import com.softserveinc.moviedbapp.model.Movie;
import com.softserveinc.moviedbapp.util.MovieAppConstants;
import com.softserveinc.moviedbapp.widget.UpdateService;

public class MovieDBMainActivity extends FragmentActivity implements OnMovieSelectedListener {

	private static final String TAG = MovieDBMainActivity.class.getSimpleName();
	private Movie mMovie;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		setTheme(com.actionbarsherlock.R.style.Theme_Sherlock);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		/* set custom style action bar */
		getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		getSupportActionBar().setCustomView(R.layout.action_bar_progress_bar);

		Intent intent = getIntent();
		if (intent.getAction().equals(UpdateService.SHOW_MOVIE_DETAILS)) {

			Movie movie = (Movie) intent.getParcelableExtra(MovieAppConstants.MOVIE_OBJECT);
			createMovieInfoFragment(movie);
		} else {
			addMovieList();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		menu.clear();
		((MenuInflater) getMenuInflater()).inflate(R.menu.action_bar_movie_list, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {

		switch (item.getItemId()) {

			case R.id.menu_refresh:
				if (isConnected() == true) {
					forceRefresh();
				} else {
					showNoConnectionDialog();
				}

				return true;

			case R.id.menu_search:
				if (isConnected() == true) {
					return onSearchRequested();
				} else {
					showNoConnectionDialog();
				}

				return true;

			case R.id.menu_settings:
				Intent settingsActivity = new Intent(getApplicationContext(), MoviePreferences.class);
				startActivityForResult(settingsActivity, 7);

				return true;

			case R.id.menu_rate:
				Toast.makeText(this, "Rating...", Toast.LENGTH_SHORT).show();

				return true;

			case R.id.menu_share:
				startSharingActivity();
				return true;

			case R.id.menu_cinemas:
				startActivity(new Intent(this, MapViewer.class));
				return true;

			default:
				return super.onOptionsItemSelected(item);
		}
	}

	/* add movie items fragment to the frame layout */
	private void addMovieList() {
		Log.d(TAG, "addMovieList()");
		FragmentManager fragmentManager = getSupportFragmentManager();
		if (fragmentManager.findFragmentById(R.id.mainFrameLayout) == null) {
			Log.d(TAG, "addMovieList() adding new movie list fragment");
			FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

			MovieItemsFragment fragment = new MovieItemsFragment();
			fragmentTransaction.add(R.id.mainFrameLayout, fragment, MovieAppConstants.MOVIE_ITEMS);
			fragmentTransaction.commit();
		}
	}

	/* show home screen with a list of movies */
	private void showHomeScreen() {

		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		MovieItemsFragment fragment = new MovieItemsFragment();
		fragmentTransaction.replace(R.id.mainFrameLayout, fragment);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
	}

	@Override
	protected void onResume() {
		super.onResume();

		ImageView actionBarIcon = (ImageView) findViewById(R.id.actionBarAppIcon);
		actionBarIcon.setOnClickListener(new OnClickListener() {
			/* on click go to home screen */
			@Override
			public void onClick(final View paramView) {
				showHomeScreen();
			}
		});
	}

	private void forceRefresh() {
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

		MovieItemsFragment fragment = new MovieItemsFragment();
		fragment.setForceRefresh(true);

		/* replace the current fragment with new MovieItems */
		fragmentTransaction.replace(R.id.mainFrameLayout, fragment);
		fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
	}

	@Override
	public void onMovieSelected(final Movie movie) {
		if (isConnected() == true) {
			createMovieInfoFragment(movie);
		} else {
			showNoConnectionDialog();
		}
	}

	/* called when user clicks the search button */
	@Override
	protected void onNewIntent(final Intent intent) {
		/* this activity is singleTop, so it has not been restarted. That's why you need to change the intent to SEARCH */
		setIntent(intent);
		handleSearchIntent(intent);
	}

	/* get SEARCH INTENT and process the query */
	private void handleSearchIntent(final Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			doMovieSearch(query);
		}
	}

	private void createMovieInfoFragment(final Movie movie) {
		mMovie = movie;
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

		/* pack the movie object into a bundle */
		Bundle movieBundle = new Bundle();
		movieBundle.putParcelable(MovieAppConstants.MOVIE_OBJECT, movie);

		/* create a fragment and pass it the bundle */
		Fragment fragment = new MovieInfoFragment();
		fragment.setArguments(movieBundle);

		/* replace MovieItems with MovieInfo */
		fragmentTransaction.replace(R.id.mainFrameLayout, fragment);
		fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();
	}

	private void doMovieSearch(final String query) {

		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

		MovieItemsFragment fragment = new MovieItemsFragment();
		fragment.setSearchQuery(query);

		/* replace the current fragment with MovieItems */
		fragmentTransaction.replace(R.id.mainFrameLayout, fragment);
		fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTransaction.addToBackStack(null);
		fragmentTransaction.commit();

	}

	private void startSharingActivity() {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.recommend));
		intent.putExtra(Intent.EXTRA_TEXT,
				String.format("%s %.2f/10\n Url: %s", mMovie.getName(), mMovie.getRating(), mMovie.getUrl()));

		startActivity(Intent.createChooser(intent, getString(R.string.share)));
	}

	private void showNoConnectionDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		/* inform the user that there's no connection */
		builder.setMessage(R.string.no_connection).setCancelable(false)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(final DialogInterface dialog, final int id) {
						/* you don't even need to cancel this dialog */
						// dialog.cancel();
					}
				}).show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public boolean isConnected() {
		return ((MovieDBApplication) getApplication()).getDataManager().isConnected();
	}

}